package config

import (
	"fmt"
	_ "github.com/ClickHouse/clickhouse-go"
	"github.com/jmoiron/sqlx"
	"strings"
	"time"
)

var CKDB *sqlx.DB

func CkInit() {
	CKConn(GConfig.CkDB)
	//链接探活
	CkeckCkActive()
}
func CKConn(value Config_ck) {
	Uri := GetCKUrl(value.Ht, value.Host, value.Port, "false", value.User, value.Pws)
	tCKDB, err := sqlx.Open("clickhouse", Uri)
	if err != nil {
		fmt.Println(err.Error())
		panic(err.Error())
		return
	}
	if tCKDB == nil {
		fmt.Println("open url is error:" + Uri)
		panic("open url is error:" + Uri)
		return
	}
	tCKDB.SetConnMaxLifetime(time.Duration(value.IdleTimeout) * time.Second)
	tCKDB.SetMaxIdleConns(value.MaxIdle)
	tCKDB.SetMaxOpenConns(value.MaxActive)

	CKDB = tCKDB
}

func GetCKUrl(tcp, hosts, port, isdebug, user, pws string) string {
	hts := strings.Split(hosts, ",")
	if len(hts) == 1 {
		return fmt.Sprintf("%s://%s:%s?%s&%s&%s", tcp, hts[0], port, "debug="+isdebug, "username="+user, "password="+pws)
	}
	althosts := []string{}
	for key, value := range hts {
		if key == 0 {
			continue
		}
		althosts = append(althosts, value+":"+port)
	}
	return fmt.Sprintf("%s://%s:%s?%s&%s&%s&%s", tcp, hts[0], port, "debug="+isdebug, "username="+user, "password="+pws, "alt_hosts="+strings.Join(althosts, ","))
}

func CkeckCkActive() {
	go func() {
		i := 1
		for range time.NewTicker(time.Second * time.Duration(1)).C {
			if i == 5 {
				panic("ck数据库链接被重置，重启服务")
				return
			}
			errs := CKDB.Ping()
			if errs != nil {
				if strings.Contains(errs.Error(), " i/o timeout") {
					fmt.Println("clickhouse链接被重置，重新链接: " + errs.Error())
					CKConn(GConfig.CkDB)
					i++
					//panic("数据库链接被重置，重启服务: " + errs.Error())
				} else {
					fmt.Println("clickhouse is error: " + errs.Error())
				}
			}
		}
	}()
}
